import sqlite3
import os
import shutil
import argparse

def fetch_files_to_move(db_path):
    """从数据库中获取需要移动的文件信息"""
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    
    query = """
    WITH ranked_files AS (
        SELECT 
            id,
            file_path,
            ROW_NUMBER() OVER (PARTITION BY file_hash ORDER BY id ASC) as row_num
        FROM video_hash
    )
    SELECT id, file_path, row_num
    FROM ranked_files
    WHERE row_num > 1;
    """
    
    cursor.execute(query)
    files = cursor.fetchall()
    conn.close()
    return files

def move_files(src_dir, des_dir, files):
    print(f"src_dir={src_dir} ")
    print(f"des_dir={des_dir} ")
    """根据给定的源目录和目标目录移动文件"""
    for _, file_path, _ in files:
        print(f"file_path={file_path} ")
        # 获取相对于src_dir的实际文件路径
        src_file_path = os.path.join(src_dir, file_path)
        print(f"src_file_path={src_file_path} ")
        
        if not os.path.exists(src_file_path):
            print(f"警告: 源文件 {src_file_path} 不存在")
            continue
        
        # 计算目标文件路径
        des_file_path = os.path.join(des_dir, file_path)
        
        # 创建必要的目录结构
        os.makedirs(os.path.dirname(des_file_path), exist_ok=True)
        
        # 移动文件
        try:
            shutil.move(src_file_path, des_file_path)
            print(f"已移动: {src_file_path} 到 {des_file_path}")
        except Exception as e:
            print(f"移动文件时出错: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="根据数据库中的记录移动文件并保持目录结构")
    parser.add_argument('--src', required=True, help="源目录，包含要移动的文件")
    parser.add_argument('--des', required=True, help="目标目录，移动后的文件存放位置")
    args = parser.parse_args()

    src_dir = args.src
    des_dir = args.des
    db_path = os.path.join(src_dir, 'file_hash.db')  # 假设数据库位于源目录下

    files = fetch_files_to_move(db_path)
    move_files(src_dir, des_dir, files)